<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/04
 * Time: 17:52
 */

namespace Modules\Shop\Service;

use HiCommon\Repository\OrderRepository;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\GoodsSpecsRepository;
use HiCommon\Repository\ExpressRepository;
use HiCommon\Repository\GoodsProductRepository;
use phpDocumentor\Reflection\Types\Self_;

class OrderService
{
    /**
     *  获取积分订单列表（积分）
     *  hinq 2019 09 18
     *
     ***/
    public function get_index_integral(array $arr_search)
    {
        try {
            $where = self::search_handle($arr_search);//诗选条件处理

            $arr_option['with'] = ['getGoodsInfo','product_info'];
            $arr_list = OrderMallRepository::get_list_by_where($where,$arr_option);

            foreach ($arr_list as $key => &$value) {
                $value['order_status'] = OrderMallRepository::order_status($value['status'], $value['pay_status']);
            }
            $arr_list->appends($arr_search);//添加链接参数
            $arr_list = list_page_data($arr_list, $arr_search);
            $arr_list['d_num'] = OrderMallRepository::get_count_by_where(['status' => 1, 'pay_status' => 2, 'shop_id' => $where['shop_id']]);//待发货订单数量

            return hello_success('成功', $arr_list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 筛选条件处理
     */
    public function search_handle($arr_search=[])
    {
        if (!empty($arr_search['status'])) {
            $where['status'] = $arr_search['status'];
            if ($arr_search['status'] == 100) {
                $where['status'] = 1;
                $where['pay_status'] = 1;
            } elseif ($arr_search['status'] == 200) {
                $where['status'] = 1;
                $where['pay_status'] = 2;
            }
        }
        if (!empty($arr_search['order_no'])) {
            $where['order_no'] = $arr_search['order_no'];
        }

        if (!empty($arr_search['range'])) {
            $where['range'] = $arr_search['range'];
        }

        $where['shop_id'] = shop_shop_id();//商户id

        return $where;
    }

    /**
     *  订单详情
     *  hinq 2019 09 18
     *
     **/
    public function order_details(int $nId)
    {// get_admin_role_id();管理员角色
        try {
            if (empty($nId)) {
                return hello_error('参数错误');
            }
            //获取订单详情
            $arr_option['with'] = ['getGoodsInfo', 'getUserInfo', 'getAddressInfo','product_info','getExpressInfo'];
            $info = OrderMallRepository::get_one((int)$nId, (array)$arr_option)->toArray();

            $info['order_state'] = OrderMallRepository::order_status($info['status'], $info['pay_status']);
            $info['xpress'] = ExpressRepository::get_all()->toArray();//快递公司列表

            return hello_success('获取成功', $info);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    //获取订单列表（导出Excel）
    public function get_order_list($arr_search)
    {
        try {
            $arr_option['where'] = self::search_handle($arr_search);//诗选条件处理
            $arr_option['with'] = ['getGoodsInfo', 'getUserInfo', 'getAddressInfo','product_info','getExpressInfo'];
            $data = OrderMallRepository::get_all($arr_option)->toArray();
            foreach ($data as $key => &$value) {
                $value['order_status'] = OrderMallRepository::order_status($value['status'], $value['pay_status']);
            }

            return $data;
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 快速发货
     */
    public function deliverGoods($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据订单id不能为空');
            }
            $map = ['id' => (int)$arr_input['id']];
            $up_data = [
                'xpress_id' => (int)$arr_input['xpress_id'],
                'delivery_no' => $arr_input['delivery_no'],
                'delivery_time' => date('Y-m-d H:i:s', time()),
                'status' => 2
            ];

            $res = OrderMallRepository::edit_one($map,$up_data);
            if ($res === false) {
                return hello_error('操作失败');
            }

            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     *  订单处理
     *
     **/
    public function changStatus($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据订单id不能为空');
            }

            return Self::cancelOrder((int)$arr_input['id']);

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 取消订单，回收库存
     */
    public function cancelOrder(int $order_id)
    {
        $map = ['id' => $order_id];
        $up_data = ['status' => 5];

        OrderMallRepository::edit_one($map,$up_data);
        $order = OrderMallRepository::get_one((int)$order_id);
        if ($order->first()) {
            $id = $order->goods_product_id;
            $num = $order->goods_num;
            if(GoodsProductRepository::increase_num($id, 'stock', $num)){
                return hello_success('成功');
            }else{
                return hello_error('库存回收失败');
            }
        }
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = OrderMallRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}